using System;
using System.Collections.Generic;
using T.FAS.Runtime.Base.Entity;
using T.FAS.Runtime.ScheduleJob.Engine;
using T.FAS.Runtime.ScheduleJob.Manager;
using T.FAS.Runtime.ScheduleJob.SPI;

namespace T.FAS.Runtime.ScheduleJob.Service
{
    public class ScheduleJobService : IScheduleJobService
    {
        private static readonly object lockObj = new object();

        private static ScheduleJobService _instance = null;

        private StdSchedulerFacotryRepository repository = null;

        private ScheduleJobExecuteService sJobExecuteService = null;
        public static IScheduleJobService GetInstance()
        {
            if (_instance == null)
            {
                lock (lockObj)
                {
                    if (_instance == null)
                        _instance = new ScheduleJobService();
                }
            }
            return _instance;
        }
        private ScheduleJobService()
        {
            repository = StdSchedulerFacotryRepository.GetInstance();
            sJobExecuteService = ScheduleJobExecuteService.GetInstance();
        }
        public ScheduleJobInstance CreateScheduleJobInstance(string jobID)
        {
            var instance = new ScheduleJobInstance();
            instance.ScheduleJobID = jobID;
            instance.Data = new ScheduleJobDataMap();
            return instance;
        }

        public ScheduleJobInstance StartJob(ScheduleJobInstance instance)
        {
            Exception ex = null;
            var start = DateTime.Now;
            try
            {
                if (instance == null)
                throw new FasException(ScheduleJobRTPExceptionCode.ScheduleJobRTPNullArgument,CommonStringClassService.ScheduleJobService_StartJob);

            if(string.IsNullOrEmpty(instance.ID))
                instance.BuildIdentity();

                //添加调度
                sJobExecuteService.Start(instance).GetAwaiter().GetResult();

                return instance;
            }
            catch (Exception e)
            {
                ex = e;
                throw new FasException(ScheduleJobRTPExceptionCode.ScheduleJobExecuteError,CommonStringClassService.ScheduleJobService_StartJob1+ex.ToString());
            }
        }

        public void PauseJob(string instanceID)
        {
            sJobExecuteService.PauseJobInstance(instanceID).GetAwaiter().GetResult();
        }

        public void ResumeJob(string instanceID)
        {
            sJobExecuteService.ResumeJobInstance(instanceID).GetAwaiter().GetResult();
        }

        public void DeleteJob(string instanceID)
        {
            sJobExecuteService.DeleteJobInstance(instanceID).GetAwaiter().GetResult();
        }

        public void ResumeAllJobs()
        {
            var serivce = sJobExecuteService;
        }

        #region 私有方法

        #endregion
    }
}
